import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;


public class FileAccess {
	
	FileReader fileReader;
	BufferedReader bufferedReader;
	String str;
	String[] temp;
	String[] temp2;
	boolean flag = true;
	ArrayList<datatype> types = new ArrayList<datatype>();
	datatype[] datatypes = new datatype[7];
	BufferedWriter bufferedWriter;
	datatype header=new datatype();
	ArrayList<String> headerFile_types = new ArrayList<String>();
	boolean matched=true;
	
	/*
	 * Function to insert record into the heap file.
	 */
	public void readFile(String fileName, String path)
	{
		datatypes[0] = new i1();
		datatypes[1] = new i2();
		datatypes[2] = new i4();
		datatypes[3] = new i8();
		datatypes[4] = new r4();
		datatypes[5] = new r8();
		datatypes[6] = new cx();
		
		try 
		{
			fileReader = new FileReader(fileName);
		} 
		catch (FileNotFoundException e) 
		{
			e.printStackTrace();
		}
		// Will give an exception if the heap file is not already present
		try{

			ReadHeader reader = new ReadHeader();
		
			temp2= reader.read(path);
			
			for(int k=0;k<temp2.length-1;k++)
				headerFile_types.add(temp2[k]);
		
			heap.created=false;
		}
			
		catch (Exception e) 
		{
			heap.f=new File(path);

		}
		
		heap.f=new File(path);
		
		bufferedReader = new BufferedReader(fileReader);
		/*
		 * Reading the header and comparing it with input csv file's schema 
		 * and inserting records if the two match.
		 */
		try 
		{
			while((str=bufferedReader.readLine())!=null)
			{
				temp = str.split(",");
				
				if(flag)
				{
					
					types = convertHeader.convertHeader(temp);
					
					if(heap.created)
					{
							str=str+","+heap.recordlength;
							header.write(str.length()+","+str,0);
					}
						
					if (headerFile_types.size()==0)
						matched = true;
					
					else if(temp.length==headerFile_types.size() )
					{
						for(int i=0;i<temp.length;i++)
						{
							if(!temp[i].equalsIgnoreCase(headerFile_types.get(i)))
							{
								matched=false;
								break;
							}
						}
					}
					else
						matched=false;
					
					flag = false;
					
				}
				
				else if (matched & !flag)
				{
					
					for(int j = 0; j < temp.length; j++ )
					{
						/*System.out.println("Heap File Length:    "+heap.f.length());
						System.out.println(j+"              "+temp[j]);
						System.out.println("..............: "+types.get(j).type);*/
						datatypes[types.get(j).type].write(temp[j],types.get(j).length);
					}
				}
				
			}
			if (matched==false)
				System.out.println("Incompatible types!!!!");
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
}
